import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gim_plugin_example/utils/data_utils.dart';
import 'package:gim_plugin_example/utils/logger_utils.dart';

import '../std.dart';

List<Widget> buildSelectChildren(List<dynamic> items, int idx, double width) {
  return items
      .asMap()
      .map((index, element) {
        double o = index == idx ? 1 : (1 - (index - idx).abs() * 0.3);
        Widget c = Container(
          alignment: Alignment.center,
          width: width,
          child: Text('$element',
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              style: TextStyle(color: blackColor, fontWeight: FontWeight.w500, fontSize: 16)),
        );
        return MapEntry(index, index == idx ? c : Opacity(opacity: o >= 0 ? o : 0, child: c));
      })
      .values
      .toList();
}

class MySinglePicker extends StatefulWidget {
  final bool selectIndex;
  final List<dynamic> items;
  dynamic item;
  final ValueChanged<dynamic>? onSelect;
  final ValueChanged<dynamic> onOk;

  MySinglePicker({this.selectIndex = false, required this.items, this.item, this.onSelect, required this.onOk});

  @override
  State<StatefulWidget> createState() => _MySinglePickerState();

  static void show(
      {required BuildContext context,
      bool? selectIndex,
      required List<dynamic> items,
      dynamic item,
      ValueChanged<dynamic>? onSelect,
      required ValueChanged<dynamic> onOk}) {
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return MySinglePicker(
            selectIndex: selectIndex ?? false,
            items: items,
            item: item,
            onSelect: onSelect,
            onOk: onOk,
          );
        });
  }
}

class _MySinglePickerState extends State<MySinglePicker> {
  FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 0);

  int idx = 0;

  @override
  void initState() {
    if (widget.item != null) {
      if (widget.selectIndex) {
        idx = widget.item ?? 0;
      } else {
        idx = widget.items.indexOf(widget.item);
      }
      loggerDebug(idx);
      if (idx != 0) {
        Future.delayed(Duration.zero).then((value) {
          controller.jumpToItem(idx);
        });
      }
    }
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: windowWidth,
            padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
            decoration: const BoxDecoration(color: Colors.black),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                    child: text16('取消', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      if (widget.item != null) {
                        if (widget.selectIndex) {
                          widget.onOk(widget.items.indexOf(widget.item));
                        } else {
                          widget.onOk(widget.item);
                        }
                      }
                      Navigator.of(context).pop();
                    }),
                CupertinoButton(
                    child: text16('确定', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      if (widget.selectIndex) {
                        widget.onOk(idx);
                      } else {
                        widget.onOk(widget.items[idx]);
                      }
                      Navigator.of(context).pop();
                    }),
              ],
            ),
          ),
          SizedBox(
              width: windowWidth,
              height: 220,
              child: CupertinoPicker(
                  scrollController: controller,
                  squeeze: 0.7,
                  diameterRatio: 1.5,
                  itemExtent: 26,
                  useMagnifier: true,
                  magnification: 1.5,
                  onSelectedItemChanged: (i) {
                    setState(() {
                      idx = i;
                    });
                    if (widget.onSelect != null) {
                      if (widget.selectIndex) {
                        widget.onSelect!(i);
                      } else {
                        widget.onSelect!(widget.items[i]);
                      }
                    }
                  },
                  children: buildSelectChildren(widget.items, idx, windowWidth)))
        ],
      ),
    );
  }
}

class MyDatePicker extends StatefulWidget {
  final String? year;
  final String? month;
  final String? day;
  final String? hour;
  final bool withHour;
  final int yearSubStart;
  final ValueChanged<List<String>>? onSelect;
  final ValueChanged<List<String>> onOk;

  MyDatePicker(
      {this.year,
      this.month,
      this.day,
      this.hour,
      required this.withHour,
      this.onSelect,
      required this.yearSubStart,
      required this.onOk});

  @override
  State<StatefulWidget> createState() => _MyDatePickerState();

  static void show(
      {required BuildContext context,
      String? year,
      String? month,
      String? day,
      String? hour,
      bool? withHour,
      int? yearSubStart,
      ValueChanged<List<String>>? onSelect,
      required ValueChanged<List<String>> onOk}) {
    yearSubStart ??= 0;
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return MyDatePicker(
            year: year,
            month: month,
            day: day,
            hour: hour,
            withHour: withHour ?? false,
            yearSubStart: yearSubStart!,
            onSelect: onSelect,
            onOk: onOk,
          );
        });
  }
}

class _MyDatePickerState extends State<MyDatePicker> {
  FixedExtentScrollController yearController = FixedExtentScrollController(initialItem: 0);
  FixedExtentScrollController monthController = FixedExtentScrollController(initialItem: 0);
  FixedExtentScrollController dayController = FixedExtentScrollController(initialItem: 0);
  FixedExtentScrollController hourController = FixedExtentScrollController(initialItem: 0);

  double width = windowWidth * 0.3;

  List<String> years = [];

  List<String> months = [];

  List<String> days = [];

  List<String> hours = [];

  int yearIdx = 0;
  int monthIdx = 0;
  int dayIdx = 0;
  int hourIdx = 0;

  @override
  void initState() {
    if (widget.withHour) {
      width = windowWidth * 0.25;
      for (int i = 0; i < 24; i++) {
        if (i < 10) {
          hours.add('0$i时');
        } else {
          hours.add('$i时');
        }
      }
    }
    int y = DateTime.now().year;
    for (int i = widget.yearSubStart; i < 100; i++) {
      years.add('${y - i}');
    }

    if (notBlack(widget.year)) {
      yearIdx = years.indexOf(widget.year!);
    }

    for (int i = 1; i <= 12; i++) {
      if (i < 10) {
        months.add('0$i');
      } else {
        months.add('$i');
      }
    }

    if (notBlack(widget.month)) {
      monthIdx = months.indexOf(widget.month!);
    }

    for (int i = 1; i <= 31; i++) {
      if (i < 10) {
        days.add('0$i');
      } else {
        days.add('$i');
      }
    }

    if (notBlack(widget.day)) {
      dayIdx = days.indexOf(widget.day!);
    }
    if (notBlack(widget.hour)) {
      hourIdx = hours.indexOf('${widget.hour}时');
    }
    Future.delayed(Duration.zero).then((value) {
      yearController.jumpToItem(yearIdx);
      monthController.jumpToItem(monthIdx);
      dayController.jumpToItem(dayIdx);
    });
    super.initState();
  }

  @override
  void dispose() {
    yearController.dispose();
    monthController.dispose();
    dayController.dispose();
    hourController.dispose();
    super.dispose();
  }

  void updateDays() {
    int d = 30;
    int m = monthIdx + 1;
    if (m == 2) {
      d = 28;
      var fst = years[yearIdx].substring(0, 2);
      var lst = years[yearIdx].substring(2);
      if (lst == '00') {
        if (int.parse(fst) % 4 == 0) {
          d = 29;
        }
      } else {
        if (lst.startsWith('0')) {
          if (int.parse(lst.substring(1)) % 4 == 0) {
            d = 29;
          }
        } else {
          if (int.parse(lst) % 4 == 0) {
            d = 29;
          }
        }
      }
    } else if (m == 1 || m == 3 || m == 7 || m == 8 || m == 10 || m == 12) {
      d = 31;
    }
    days = [];
    for (int i = 1; i <= d; i++) {
      if (i < 10) {
        days.add('0$i');
      } else {
        days.add('$i');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> cld = [
      SizedBox(
        width: width,
        child: CupertinoPicker(
            scrollController: yearController,
            squeeze: 0.7,
            diameterRatio: 1.5,
            itemExtent: 26,
            useMagnifier: true,
            magnification: 1.5,
            onSelectedItemChanged: (i) {
              yearIdx = i;
              if (monthIdx == 1) {
                updateDays();
              }
              if (dayIdx >= days.length) {
                dayIdx = days.length - 1;
                dayController.jumpToItem(dayIdx);
              }
              if (widget.onSelect != null) {
                var arr = [years[yearIdx], months[monthIdx], days[dayIdx]];
                if (widget.withHour) {
                  if (hourIdx < 10) {
                    arr.add('0$hourIdx');
                  } else {
                    arr.add('$hourIdx');
                  }

                }
                widget.onSelect!(arr);
              }
              setState(() {});
            },
            children: buildSelectChildren(years, yearIdx, width)),
      ),
      SizedBox(
        width: width,
        child: CupertinoPicker(
            scrollController: monthController,
            squeeze: 0.7,
            diameterRatio: 1.5,
            itemExtent: 26,
            useMagnifier: true,
            magnification: 1.5,
            onSelectedItemChanged: (i) {
              monthIdx = i;
              updateDays();
              if (dayIdx >= days.length) {
                dayIdx = days.length - 1;
                dayController.jumpToItem(dayIdx);
              }
              if (widget.onSelect != null) {
                var arr = [years[yearIdx], months[monthIdx], days[dayIdx]];
                if (widget.withHour) {
                  if (hourIdx < 10) {
                    arr.add('0$hourIdx');
                  } else {
                    arr.add('$hourIdx');
                  }

                }
                widget.onSelect!(arr);
              }
              setState(() {});
            },
            children: buildSelectChildren(months, monthIdx, width)),
      ),
      SizedBox(
        width: width,
        child: CupertinoPicker(
            scrollController: dayController,
            squeeze: 0.7,
            diameterRatio: 1.5,
            itemExtent: 26,
            useMagnifier: true,
            magnification: 1.5,
            onSelectedItemChanged: (i) {
              dayIdx = i;
              if (widget.onSelect != null) {
                var arr = [years[yearIdx], months[monthIdx], days[dayIdx]];
                if (widget.withHour) {
                  if (hourIdx < 10) {
                    arr.add('0$hourIdx');
                  } else {
                    arr.add('$hourIdx');
                  }

                }
                widget.onSelect!(arr);
              }
              setState(() {});
            },
            children: buildSelectChildren(days, dayIdx, width)),
      ),
    ];

    if (widget.withHour) {
      cld.add(SizedBox(
        width: width,
        child: CupertinoPicker(
            scrollController: hourController,
            squeeze: 0.7,
            diameterRatio: 1.5,
            itemExtent: 26,
            useMagnifier: true,
            magnification: 1.5,
            onSelectedItemChanged: (i) {
              hourIdx = i;
              if (widget.onSelect != null) {
                var arr = [years[yearIdx], months[monthIdx], days[dayIdx]];
                if (widget.withHour) {
                  if (hourIdx < 10) {
                    arr.add('0$hourIdx');
                  } else {
                    arr.add('$hourIdx');
                  }
                }
                widget.onSelect!(arr);
              }
              setState(() {});
            },
            children: buildSelectChildren(hours, hourIdx, width)),
      ));
    }

    return Material(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: windowWidth,
            padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
            decoration: const BoxDecoration(color: Colors.black),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                    child: text16('取消', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      if (notBlack(widget.year) && notBlack(widget.month) && notBlack(widget.day)) {
                        var arr = [widget.year!, widget.month!, widget.day!];
                        if (widget.hour != null) {
                          arr.add(widget.hour!);
                        }
                        widget.onOk(arr);
                      }
                      Navigator.of(context).pop();
                    }),
                CupertinoButton(
                    child: text16('确定', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      var arr = [years[yearIdx], months[monthIdx], days[dayIdx]];
                      if (widget.withHour) {
                        if (hourIdx < 10) {
                          arr.add('0$hourIdx');
                        } else {
                          arr.add('$hourIdx');
                        }

                      }
                      widget.onOk(arr);
                      Navigator.of(context).pop();
                    }),
              ],
            ),
          ),
          SizedBox(
              width: windowWidth,
              height: 220,
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: cld,
              ))
        ],
      ),
    );
  }
}

class MyPcPicker extends StatefulWidget {
  final String? province;
  final String? city;
  final ValueChanged<List<String>>? onSelect;
  final ValueChanged<List<String>> onOk;

  MyPcPicker({this.province, this.city, this.onSelect, required this.onOk});

  @override
  State<StatefulWidget> createState() => _MyPcPickerState();

  static void show(
      {required BuildContext context,
      String? province,
      String? city,
      ValueChanged<List<String>>? onSelect,
      required ValueChanged<List<String>> onOk}) {
    showCupertinoModalPopup(
        context: context,
        builder: (BuildContext context) {
          return MyPcPicker(
            province: province,
            city: city,
            onSelect: onSelect,
            onOk: onOk,
          );
        });
  }
}

class _MyPcPickerState extends State<MyPcPicker> {
  FixedExtentScrollController provinceController = FixedExtentScrollController(initialItem: 0);
  FixedExtentScrollController cityController = FixedExtentScrollController(initialItem: 0);

  final width = windowWidth * 0.4;

  List<dynamic> provinces = [];
  List<dynamic> cities = [];
  int provinceIdx = 0;
  int cityIdx = 0;

  @override
  void initState() {
    provinces = pc.keys.toList();
    if (notBlack(widget.province)) {
      provinceIdx = provinces.indexOf(widget.province!);
    }
    cities = pc[provinces[provinceIdx]]!;
    if (notBlack(widget.city)) {
      cityIdx = cities.indexOf(widget.city!);
    }
    Future.delayed(Duration.zero).then((value) {
      provinceController.jumpToItem(provinceIdx);
      cityController.jumpToItem(cityIdx);
    });
    super.initState();
  }

  @override
  void dispose() {
    provinceController.dispose();
    cityController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: windowWidth,
            padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
            decoration: const BoxDecoration(color: Colors.black),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CupertinoButton(
                    child: text16('取消', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      if (notBlack(widget.province) && notBlack(widget.city)) {
                        widget.onOk([widget.province!, widget.city!]);
                      }
                      Navigator.of(context).pop();
                    }),
                CupertinoButton(
                    child: text16('确定', color: Colors.white),
                    padding: EdgeInsets.zero,
                    onPressed: () {
                      widget.onOk([provinces[provinceIdx], cities[cityIdx]]);
                      Navigator.of(context).pop();
                    }),
              ],
            ),
          ),
          SizedBox(
              width: windowWidth,
              height: 220,
              child: Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  SizedBox(
                    width: width,
                    child: CupertinoPicker(
                        scrollController: provinceController,
                        squeeze: 0.7,
                        diameterRatio: 1.5,
                        itemExtent: 26,
                        useMagnifier: true,
                        magnification: 1.5,
                        onSelectedItemChanged: (i) {
                          setState(() {
                            provinceIdx = i;
                            cities = pc[provinces[i]]!;
                            if (cityIdx >= cities.length) {
                              cityIdx = cities.length - 1;
                              cityController.jumpToItem(cityIdx);
                            }
                          });
                          if (widget.onSelect != null) {
                            widget.onSelect!([provinces[provinceIdx], cities[cityIdx]]);
                          }
                        },
                        children: buildSelectChildren(provinces, provinceIdx, width)),
                  ),
                  SizedBox(
                    width: width,
                    child: CupertinoPicker(
                        scrollController: cityController,
                        squeeze: 0.7,
                        diameterRatio: 1.5,
                        itemExtent: 26,
                        useMagnifier: true,
                        magnification: 1.5,
                        onSelectedItemChanged: (i) {
                          setState(() {
                            cityIdx = i;
                          });
                          if (widget.onSelect != null) {
                            widget.onSelect!([provinces[provinceIdx], cities[cityIdx]]);
                          }
                        },
                        children: buildSelectChildren(cities, cityIdx, width)),
                  ),
                ],
              ))
        ],
      ),
    );
  }

  Map<String, List<String>> pc = {
    "北京市": ["北京市"],
    "天津市": ["天津市"],
    "河北省": ["石家庄市", "唐山市", "秦皇岛市", "邯郸市", "邢台市", "保定市", "张家口市", "承德市", "沧州市", "廊坊市", "衡水市"],
    "山西省": ["太原市", "大同市", "阳泉市", "长治市", "晋城市", "朔州市", "晋中市", "运城市", "忻州市", "临汾市", "吕梁市"],
    "内蒙古自治区": ["呼和浩特市", "包头市", "乌海市", "赤峰市", "通辽市", "鄂尔多斯市", "呼伦贝尔市", "巴彦淖尔市", "乌兰察布市", "兴安盟", "锡林郭勒盟", "阿拉善盟"],
    "辽宁省": ["沈阳市", "大连市", "鞍山市", "抚顺市", "本溪市", "丹东市", "锦州市", "营口市", "阜新市", "辽阳市", "盘锦市", "铁岭市", "朝阳市", "葫芦岛市"],
    "吉林省": ["长春市", "吉林市", "四平市", "辽源市", "通化市", "白山市", "松原市", "白城市", "延边自治州"],
    "黑龙江省": ["哈尔滨市", "齐齐哈尔市", "鸡西市", "鹤岗市", "双鸭山市", "大庆市", "伊春市", "佳木斯市", "七台河市", "牡丹江市", "黑河市", "绥化市", "大兴安岭"],
    "上海市": ["上海市"],
    "江苏省": ["南京市", "无锡市", "徐州市", "常州市", "苏州市", "南通市", "连云港市", "淮安市", "盐城市", "扬州市", "镇江市", "泰州市", "宿迁市"],
    "浙江省": ["杭州市", "宁波市", "温州市", "嘉兴市", "湖州市", "绍兴市", "金华市", "衢州市", "舟山市", "台州市", "丽水市"],
    "安徽省": [
      "合肥市",
      "芜湖市",
      "蚌埠市",
      "淮南市",
      "马鞍山市",
      "淮北市",
      "铜陵市",
      "安庆市",
      "黄山市",
      "滁州市",
      "阜阳市",
      "宿州市",
      "六安市",
      "亳州市",
      "池州市",
      "宣城市"
    ],
    "福建省": ["福州市", "厦门市", "莆田市", "三明市", "泉州市", "漳州市", "南平市", "龙岩市", "宁德市"],
    "江西省": ["南昌市", "景德镇市", "萍乡市", "九江市", "新余市", "鹰潭市", "赣州市", "吉安市", "宜春市", "抚州市", "上饶市"],
    "山东省": [
      "济南市",
      "青岛市",
      "淄博市",
      "枣庄市",
      "东营市",
      "烟台市",
      "潍坊市",
      "济宁市",
      "泰安市",
      "威海市",
      "日照市",
      "临沂市",
      "德州市",
      "聊城市",
      "滨州市",
      "菏泽市"
    ],
    "河南省": [
      "郑州市",
      "开封市",
      "洛阳市",
      "平顶山市",
      "安阳市",
      "鹤壁市",
      "新乡市",
      "焦作市",
      "濮阳市",
      "许昌市",
      "漯河市",
      "三门峡市",
      "南阳市",
      "商丘市",
      "信阳市",
      "周口市",
      "驻马店市",
      "济源市"
    ],
    "湖北省": [
      "武汉市",
      "黄石市",
      "十堰市",
      "宜昌市",
      "襄阳市",
      "鄂州市",
      "荆门市",
      "孝感市",
      "荆州市",
      "黄冈市",
      "咸宁市",
      "随州市",
      "恩施",
      "仙桃市",
      "潜江市",
      "天门市",
      "神农架林区"
    ],
    "湖南省": ["长沙市", "株洲市", "湘潭市", "衡阳市", "邵阳市", "岳阳市", "常德市", "张家界市", "益阳市", "郴州市", "永州市", "怀化市", "娄底市", "湘西"],
    "广东省": [
      "广州市",
      "韶关市",
      "深圳市",
      "珠海市",
      "汕头市",
      "佛山市",
      "江门市",
      "湛江市",
      "茂名市",
      "肇庆市",
      "惠州市",
      "梅州市",
      "汕尾市",
      "河源市",
      "阳江市",
      "清远市",
      "东莞市",
      "中山市",
      "潮州市",
      "揭阳市",
      "云浮市"
    ],
    "广西": ["南宁市", "柳州市", "桂林市", "梧州市", "北海市", "防城港市", "钦州市", "贵港市", "玉林市", "百色市", "贺州市", "河池市", "来宾市", "崇左市"],
    "海南省": [
      "海口市",
      "三亚市",
      "三沙市",
      "儋州市",
      "五指山市",
      "琼海市",
      "文昌市",
      "万宁市",
      "东方市",
      "定安县",
      "屯昌县",
      "澄迈县",
      "临高县",
      "白沙",
      "昌江",
      "乐东",
      "陵水",
      "保亭",
      "琼中"
    ],
    "重庆市": ["重庆市"],
    "四川省": [
      "成都市",
      "自贡市",
      "攀枝花市",
      "泸州市",
      "德阳市",
      "绵阳市",
      "广元市",
      "遂宁市",
      "内江市",
      "乐山市",
      "南充市",
      "眉山市",
      "宜宾市",
      "广安市",
      "达州市",
      "雅安市",
      "巴中市",
      "资阳市",
      "阿坝",
      "甘孜",
      "凉山"
    ],
    "贵州省": ["贵阳市", "六盘水市", "遵义市", "安顺市", "毕节市", "铜仁市", "黔西南", "黔东南", "黔南"],
    "云南省": ["昆明市", "曲靖市", "玉溪市", "保山市", "昭通市", "丽江市", "普洱市", "临沧市", "楚雄", "红河", "文山", "西双版纳", "大理", "德宏", "怒江", "迪庆"],
    "西藏自治区": ["拉萨市", "日喀则市", "昌都市", "林芝市", "山南市", "那曲市", "阿里地区"],
    "陕西省": ["西安市", "铜川市", "宝鸡市", "咸阳市", "渭南市", "延安市", "汉中市", "榆林市", "安康市", "商洛市"],
    "甘肃省": ["兰州市", "嘉峪关市", "金昌市", "白银市", "天水市", "武威市", "张掖市", "平凉市", "酒泉市", "庆阳市", "定西市", "陇南市", "临夏", "甘南"],
    "青海省": ["西宁市", "海东市", "海北", "黄南", "海南", "果洛", "玉树", "海西"],
    "宁夏": ["银川市", "石嘴山市", "吴忠市", "固原市", "中卫市"],
    "新疆": [
      "乌鲁木齐市",
      "克拉玛依市",
      "吐鲁番市",
      "哈密市",
      "昌吉",
      "博尔塔拉",
      "巴音郭楞",
      "阿克苏",
      "喀什",
      "和田",
      "伊犁",
      "塔城",
      "阿勒泰",
      "石河子市",
      "阿拉尔市",
      "图木舒克市",
      "五家渠市",
      "北屯市",
      "铁门关市",
      "双河市",
      "可克达拉市",
      "昆玉市",
      "胡杨河市",
      "新星市"
    ]
  };
}
